﻿using Edu.Http.Proxy;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Shared.Service.Http.Proxy;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Yyd.Share.Base;

namespace Shared.Service.Authorizations.Authorization.HttpApis
{
    public class DataScopesHttpApi : BaseHttpClient, IDataScopesHttpApi
    {
        private static readonly  string DataScopesUrl = "api/uc/auth/user/menucode/datapolicy";
        private static readonly string CheckcodeUrl = "api/uc/auth/user/checkcode";

        public DataScopesHttpApi(HttpClient client, ILoggerFactory loggerFactory,
            IOptions<WebApiClientOptions> webApiClientOptions) : base(client,
            loggerFactory, "")
        {
            this._client.BaseAddress = new Uri(webApiClientOptions.Value.HttpHosts.AuthUser);
        }

        public async Task<Dictionary<string, string[]>> GetUserDataScopesAsync(GetUserDataScopesRequest @params)
        {
           // var url = _webApiClientOptions.HttpHosts.AuthUser + DataScopesUrl;

            var formStr = ConvertRequestToCommonFormUrlEncode(@params);

            var result = await GetAsync<HttpApiResult>(DataScopesUrl + "?" + formStr + "&pageid=" + Guid.NewGuid());
            if (!result.Success)
            {
                throw new OperationException(StatusCodes.Status404NotFound, result.Msg);
            }

            if (result.Data?.HasValues ?? false)
            {
                return result.Data.ToObject<Dictionary<string, string[]>>();
            }

            throw new OperationException(StatusCodes.Status404NotFound, result.Msg);
        }

        public async Task<PermissionGrantResult> IsGrantedAsync(GetIsGrantedRequest @params)
        {
           // var url = _webApiClientOptions.HttpHosts.AuthUser + CheckcodeUrl;

            var formStr = ConvertRequestToCommonFormUrlEncode(@params);

            var result = await GetAsync<HttpApiResult>(CheckcodeUrl
                                                       + "?" + formStr + "&pageid=" + Guid.NewGuid());
            if (!result.Success)
            {
                throw new OperationException(StatusCodes.Status404NotFound, result.Msg);
            }

            if (result.Data?.HasValues ?? false)
            {
                return result.Data.ToObject<PermissionGrantResult>();
            }

            throw new OperationException(StatusCodes.Status404NotFound, result.Msg);
        }
    }
}
